package com.chengh.vhr.config;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 分析当前主体是否具备刚刚分析出来的权限
 */
@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {

    /**
     *
     * @param authentication 主体,当前用户
     * @param object
     * @param configAttributes 能够访问这个地址的角色
     * @throws AccessDeniedException
     * @throws InsufficientAuthenticationException
     */
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
        for (ConfigAttribute configAttribute : configAttributes) {
            String needRole = configAttribute.getAttribute();

            //上文打的标记,但是需要判断用户是否登录
            if("ROLE_LOGIN".equals(needRole)) {
                //判断是否登录
                if(authentication instanceof AnonymousAuthenticationToken) {
                    throw new AccessDeniedException("请登录后再访问!");
                }else {
                    //此处直接放行
                    return;
                }
            }
            // 把当前分析出来的地址角色跟访问这个地址需要的权限做比较
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();//获取当前用户登录的角色
            for (GrantedAuthority authority : authorities) {
                if(authority.getAuthority().equals(needRole)) {
                    //匹配上了,直接放行
                    return;
                }
            }
        }
        //如果什么角色都没有,那就直接给出权限不足的提示
        throw new AccessDeniedException("权限不足,请联系管理员!");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
